package com.ok.common.utils

import android.app.Activity
import android.app.ActivityManager
import android.content.Context
import android.view.KeyEvent
import com.ok.common.R
import com.ok.common.ext.toast
import java.util.*
import kotlin.system.exitProcess

/**
 * 退出应用
 * 1. 在Activity中重写onKeyDown方法
 * 2. 在onKeyDown方法中调用帮助类的onKeyDown方法
 */
object AppExitUtils {
    /*  */
    private var isExit: Boolean = false
    private var hasTask: Boolean = false
    private var tExit = Timer()
    private var task: TimerTask = object : TimerTask() {
        override fun run() {
            isExit = false
            hasTask = true
        }
    }

    fun onKeyDown(context: Context, keyCode: Int): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!isExit) {
                isExit = true
                context.toast(context.getString(R.string.exit_app))
                if (!hasTask) tExit.schedule(task, 2000)
            } else {
                appExit(context)
            }
        }
        return false
    }

    /**
     * 退出应用程序
     */
    fun appExit(context: Context) {
        try {
            (context as Activity).finish()
            val activityMgr = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
            activityMgr.killBackgroundProcesses(context.packageName)
            exitProcess(0)
        } catch (e: Exception) {
            exitProcess(0)
        }

    }
}